package com.tanhua.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.mapper.UserAdminMapper;
import com.tanhua.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class userAdminService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserAdminMapper userAdminMapper;
    @Value("${jwt.secret}")
    private String secret;

    public Map<String, String> login(String username, String password, String verificationCode, String uuid) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).eq("password", password);
        User user = (User) userAdminMapper.selectOne(queryWrapper);
        if (user != null) {
            String code = (String) redisTemplate.opsForValue().get(uuid);
            if (code.equals(verificationCode)) {
                redisTemplate.delete(uuid);
                //生成token
                Map<String, Object> claims = new HashMap<String, Object>();
                claims.put("id", user.getId());
                String token = Jwts.builder()
                        .setClaims(claims)
                        .signWith(SignatureAlgorithm.HS256, secret)
                        .setExpiration(new DateTime().plusHours(12).toDate())
                        .compact();
                //把token放入redis
                String redisKey = "VERIFICATION_CODE_"+uuid;
                redisTemplate.opsForValue().set(redisKey,token);
                //返回token
                Map<String, String> tokenMap = new HashMap<>();
                tokenMap.put("token", token);
                return tokenMap;

            }
        }

        return null;
    }


}
